package com.zx.zxapibackend.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWTHeader;
import cn.hutool.jwt.JWTPayload;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.RegisteredPayload;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 张旭
 * @version 1.0
 */
@Component
@Slf4j
public class TokenUtils {

    //todo 将生成的token存入redis中
    //盐
    private final String salt = "zxapi-shadowman";
    //签名加盐:约定使用HS512算法
    private final JWTSigner signer = JWTSignerUtil.hs512(salt.getBytes(StandardCharsets.UTF_8));

    /**
     * 生成token
     *
     * @param id
     * @param userAccount
     * @return
     */
    public String generateToken(String id, String userAccount) {
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.HOUR, 720);//过期时间720小时
        //创建payload
        Map<String, Object> payload = new HashMap<>();
        payload.put("id", id);
        payload.put("userAccount", userAccount);
        //签发时间
        payload.put(RegisteredPayload.ISSUED_AT, now);
        //过期时间
        payload.put(RegisteredPayload.EXPIRES_AT, newTime);
        String token = JWTUtil.createToken(payload, signer);
        return token;
    }

    /**
     * 验证token是否合法
     *
     * @param token
     * @return
     */
    public boolean verifyToken(String token) {
        try {
            JWT jwt = JWTUtil.parseToken(token);
            String algorithm = jwt.getAlgorithm();
            if(null==algorithm||!"HS512".equals(algorithm)){
                return false;
            }
            boolean verify = jwt.setSigner(signer).verify();
            if(!verify){
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("verify方法错误——》{}",e.toString());
            return false;
        }
    }

    /**
     * 验证token是否过期
     *
     * @param token
     * @return
     */
    public boolean verifyTime(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        boolean validate = jwt.validate(0);
        if(validate){
            return false;
        }
        return true;
    }

    /**
     * 刷新token
     *
     * @param token
     * @return
     */
    public String refreshToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        String id = (String) jwt.getPayload("id");
        String userAccount = (String) jwt.getPayload("userAccount");

        String newToken = generateToken(id, userAccount);
        return newToken;
    }
}
